package org.example.user.service;

import lombok.extern.slf4j.Slf4j;
import org.example.user.api.UserApi;
import org.example.user.data.entity.UserEntity;
import org.example.user.data.form.UserCreateForm;
import org.example.user.data.view.UserInfo;
import org.example.user.service.storage.UserEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component
public class UserService implements UserApi {

    @Autowired
    private UserEntityMapper userEntityMapper;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public UserInfo addUser(UserCreateForm userTo) {

        UserEntity userEntity = transformFrom(userTo);

        Integer result = userEntityMapper.insertUserEntity(userEntity);

        if(1 != result){
            return null;

        }

        return transformTo(userEntity);

    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public UserInfo getUser(UserInfo userInfo) {

        UserEntity userEntity = userEntityMapper.selectUserEntityById(userInfo.getId());

        if(null == userEntity){
            return null;

        }

        return transformTo(userEntity);

    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public UserInfo loginUser(String account, String password) {

        UserEntity userEntity = userEntityMapper.selectByAccountAndPassword(account, password);

        if(null == userEntity){
            return null;

        }

        return transformTo(userEntity);

    }

    private UserEntity transformFrom(UserCreateForm userCreateTO){

        UserEntity userEntity = new UserEntity();

        userEntity.setAccount(userCreateTO.getAccount());
        userEntity.setPassword(userCreateTO.getPassword());
        userEntity.setDisplayName(userCreateTO.getDisplayName());
        userEntity.setDisplayImage(userCreateTO.getDisplayImage());
        userEntity.setState(userCreateTO.getState());
        userEntity.setCreateTimestamp(userCreateTO.getCreateTimestamp());

        return userEntity;

    }

    private UserInfo transformTo(UserEntity userEntity){

        UserInfo userInfo = new UserInfo();

        userInfo.setId(userEntity.getId());
        userInfo.setDisplayName(userEntity.getDisplayName());
        userInfo.setDisplayImage(userEntity.getDisplayImage());

        return userInfo;

    }

}
